<template>
    <div>
        <!-- 筛选区域 -->
        <el-form :inline="true" class="filter-form">
            <el-form-item label="供应商编号">
                <el-input placeholder="请输入" v-model="page.supplierNumber"></el-input>
            </el-form-item>
            <el-form-item label="供应商名称">
                <el-input placeholder="请输入" v-model="page.supplierName"></el-input>
            </el-form-item>
            <el-form-item label="类型">
                <el-select v-model="page.orderAmount" placeholder="选择类型" style="width: 200px;">
                    <el-option label="选择类型" value="" />
                    <el-option label="合作供应商" value="合作供应商" />
                    <el-option label="协作供应商" value="协作供应商" />
                </el-select>
            </el-form-item>
            <el-form-item label="电话">
                <el-input placeholder="请输入" v-model="page.supplierPhone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="GetFinanceList">查询</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 操作按钮区域 -->
        <div class="action-buttons">

            <el-button type="success" @click="tk.IsAdd = true" round>新增</el-button>
            <el-button type="warning" @click="tk.IsUpdate = true" round>编辑</el-button>
            <el-button type="danger" @click="handleClickShow" round>删除</el-button>
            <el-button color="#626aef">刷新</el-button>
            <el-button type="primary" @click="commandShow">导出</el-button>
        </div>
        <!-- 数据表格区域 -->
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="supplierNumber" label="供应商编号"></el-table-column>
            <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
            <el-table-column prop="orderAmount" label="供应商类型"></el-table-column>
            <el-table-column prop="supplierPhone" label="电话"></el-table-column>
            <el-table-column prop="chuanZhen" label="传真"></el-table-column>
            <el-table-column prop="email" label="Email"></el-table-column>
            <el-table-column prop="supplierNamer" label="联系人"></el-table-column>
            <el-table-column prop="supplierAdd" label="地址"></el-table-column>
            <el-table-column prop="supplierTime" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
                <template v-slot="scoped">
                    <el-button type="danger" @click="del(scoped.row.supplierId)" size="small">删除</el-button>
                    <el-button link size="small" type="primary" @click="upd(scoped.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="tk.IsAdd" title="新增供应商" :draggable="true" width="500" append-to-body>
            <el-form :model="bd" label-width="80px">
                <el-form-item label="供应商名称">
                    <el-input v-model="bd.supplierName"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="bd.supplierPhone"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select placeholder="请选择" v-model="bd.orderAmount">
                        <el-option label="合作供应商" value="合作供应商" />
                        <el-option label="协作供应商" value="协作供应商" />
                        <!-- 可根据实际情况添加更多选项 -->
                    </el-select>
                </el-form-item>
                <el-form-item label="传真">
                    <el-input v-model="bd.chuanZhen"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="bd.email"></el-input>
                </el-form-item>
                <el-form-item label="联系人">
                    <el-input v-model="bd.supplierNamer"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="bd.supplierAdd"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="tk.IsAdd = false">取消</el-button>
                <el-button type="primary" @click="Save">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="tk.IsUpdate" title="修改供应商" :draggable="true" width="500" append-to-body>
            <el-form :model="bd" label-width="80px">
                <el-form-item label="供应商名称">
                    <el-input v-model="bd.supplierName"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="bd.supplierPhone"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select placeholder="请选择" v-model="bd.orderAmount">
                        <el-option label="合作供应商" value="合作供应商" />
                        <el-option label="协作供应商" value="协作供应商" />
                        <!-- 可根据实际情况添加更多选项 -->
                    </el-select>
                </el-form-item>
                <el-form-item label="传真">
                    <el-input v-model="bd.chuanZhen"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="bd.email"></el-input>
                </el-form-item>
                <el-form-item label="联系人">
                    <el-input v-model="bd.supplierNamer"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="bd.supplierAdd"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="tk.IsUpdate = false">取消</el-button>
                <el-button type="primary" @click="update">确定</el-button>
            </template>
        </el-dialog>

        <!-- 分页区域 -->
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="page.TotalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { KongaUrl } from '@/axios/axiosHelp'
const route = useRoute()

//分页
const page = reactive({
    "supplierNumber": "",
    "supplierName": "",
    "orderAmount": "",
    "supplierPhone": "",
    PageIndex: 1,
    PageSize: 15,
    TotalCount: 0,
    PageCount: 0,
})

const tk = reactive({
    //新增
    IsAdd: false,
    //编辑
    IsUpdate: false,
})

// 重置方法
const reset = () => {
    bd.supplierNumber = ''
    bd.supplierName = ''
    bd.supplierPhone = ''
    bd.orderAmount = ''
}

const bd = reactive({
    "supplierId": 0,
    "supplierNumber": "",
    "supplierName": "",
    "orderAmount": "合作供应商",
    "supplierPhone": "",
    "chuanZhen": "",
    "email": "",
    "supplierNamer": "",
    "supplierAdd": "",
    "supplierTime": "2025-03-29"
})

const Save = () => {
    KongaUrl.post("/xin1/api/ManagSupplierController/SupplierAdd", bd).then(res => {
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            tk.IsAdd = false;
            GetFinanceList();
        }
        else {
            ElMessage.error("添加失败");
        }
    })
}

const tableData = ref([])

const GetFinanceList = () => {
    KongaUrl.get("/xin/api/ManagSupplier/SupplierQuery", {
        params: {
            supplierNumber: page.supplierNumber,
            supplierName: page.supplierName,
            supplierPhone: page.supplierPhone,
            orderAmount: page.orderAmount,
            PageIndex: page.PageIndex,
            PageSize: page.PageSize
        }
    }).then(res => {
        tableData.value = res.data.lists
        page.TotalCount = res.data.totalCount
        page.PageCount = res.data.pageCount
    })
}

//分页
const handleSizeChange = (index: any) => {
    page.PageSize = index
    GetFinanceList()
}
const handleCurrentChange = (index: any) => {
    page.PageIndex = index;
    GetFinanceList()
}

// 批量删除 
const handleClickShow = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.error('请至少选择一条记录');
        return;
    }
    try {
        const confirmResult = await ElMessageBox.confirm('是否确认删除选中的记录？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        if (confirmResult === 'confirm') {
            const ids = selectedRows.value.map(row => row.supplierId);
            const response = await KongaUrl.post("/xin1/api/Management/PurchaseDels", {
                data: { SupplierId: ids },
                headers: { 'Content-Type': 'application/json' }
            });

            if (response.data.code === 300) {
                ElMessage.success('删除成功');
                await GetFinanceList();
                selectedRows.value = [];
            } else {
                ElMessage.error(response.data.msg || '删除失败');
            }
        }
    } catch (error) {
        if (error instanceof Error) {
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};

//单删
const del = (supplierId: any) => {
    console.log(supplierId)
    ElMessageBox.confirm("是否确认删除?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
    }).then(() => {
        KongaUrl.post("/xin1/api/ManagSupplierController/SupplierDel?SupplierId=" + supplierId).then((res) => {
            if (res.data.code == 300) {
                ElMessage.success(res.data.msg);
                GetFinanceList();
            } else {
                ElMessage.error(res.data.msg);
            }
        });
    });
};

//反填
const upd = (row: any) => {
    bd.supplierId = row.supplierId,
        bd.supplierNumber = row.supplierNumber,
        bd.supplierName = row.supplierName,
        bd.orderAmount = row.orderAmount,
        bd.supplierPhone = row.supplierPhone,
        bd.chuanZhen = row.chuanZhen,
        bd.email = row.email,
        bd.supplierNamer = row.supplierNamer,
        bd.supplierAdd = row.supplierAdd,
        bd.supplierTime = row.supplierTime,
        tk.IsUpdate = true
}
//修改
const update = (row: any) => {
    KongaUrl.put("/xin/api/ManagSupplierController/SupplierUpd", bd)
        .then(res => {
            if (res.data.code == 400) {
                ElMessage.success(res.data.msg)
                tk.IsUpdate = false
                GetFinanceList()
            }
            else {
                ElMessage.error(res.data.msg)
                return
            }
        })
}

//多选按钮存入数据
const selectedRows = ref<any[]>([]) // 存储选中行的数据
// 多选事件回调
const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows // 将选中的行数据保存到变量中
}

//导出
const commandShow = async () => {
    const ids = selectedRows.value.map(row => row.supplierId);
    if (!ids.length) {
        ElMessage.error('请选择需要导出的商品');
        return;
    }

    try {
        // 构建参数
        const queryParams = ids.map(id => `supplierId=${id}`).join('&');
        const url = `/xin/api/ManagSupplier/SupplierExportOrderList?${queryParams}`;

        // 发送请求获取二进制流
        const response = await axios.get(url, {
            responseType: 'arraybuffer', // 明确响应类型为二进制
        });

        // 解析文件名（从响应头获取）
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition?.match(/filename="?([^"]+)"/)?.[1] || '商品列表.xlsx';

        // 生成Blob并触发下载
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = fileName;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(downloadUrl);

    } catch (error) {
        console.error('导出错误:', error);
        ElMessage.error(`导出失败: ${error.message}`);
    }
};


onMounted(() => {
    GetFinanceList()
})

</script>

<style scoped>
.filter-form {
    margin-bottom: 10px;
}

.action-buttons {
    margin-bottom: 10px;
}
</style>